'use client';
import React, { useState, useContext } from 'react';
import Particles from 'react-tsparticles';
import { loadSlim } from 'tsparticles-slim';
import { Engine } from 'tsparticles-engine';
import http from '@/lib/request';
import { ApiResponse, LoginRes } from '@/types/interface';
import { useRouter } from 'next/navigation';
import { setSesstion } from '@/lib/session';
import { AuthContext } from '@/context/auth-context';

// 用户图标 SVG
const UserIcon = () => (
  <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
  </svg>
);

// 锁图标 SVG
const LockIcon = () => (
  <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
  </svg>
);

type FieldType = {
  username?: string;
  password?: string;
  remember?: boolean;
};

type FormErrors = {
  username?: string;
  password?: string;
};

// 眼睛图标 SVG（显示密码）
const EyeIcon = () => (
  <svg className="w-5 h-5 text-gray-400 hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
  </svg>
);

// 眼睛关闭图标 SVG（隐藏密码）
const EyeOffIcon = () => (
  <svg className="w-5 h-5 text-gray-400 hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
  </svg>
);

export default function AiLoginPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const { setUser } = useContext(AuthContext);
  const [formValues, setFormValues] = useState<FieldType>({
    username: '',
    password: '',
    remember: true
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [showPassword, setShowPassword] = useState(false);
  const [globalError, setGlobalError] = useState<string>('');
  
  const particlesInit = async (engine: Engine) => {
    await loadSlim(engine);
  };

  // 表单验证函数
  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};
    
    if (!formValues.username?.trim()) {
      newErrors.username = 'Please input your username!';
    }
    
    if (!formValues.password?.trim()) {
      newErrors.password = 'Please input your password!';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 表单字段变化处理
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setFormValues(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // 清除对应字段的错误
    if (errors[name as keyof FormErrors]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name as keyof FormErrors];
        return newErrors;
      });
    }
  };

  // 表单提交处理
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    console.log('Success:', formValues);
    setLoading(true);
    
    try {
      // 清除之前的全局错误
      setGlobalError('');
      // 调用本地登录API
      const res = (await http.post('/api/auth/login', formValues)) as ApiResponse<LoginRes>;
      
      if (res.code === 200) {
        // 设置 sessionStorage 和 cookie
        setSesstion('token', res.data.access_token);
        
        // 更新认证上下文
        const userInfo = {
          username: formValues.username,
          // 这里可以根据实际需求添加更多用户信息
        };
        setUser(userInfo);
        
        console.log('Login successful:', res);
        router.push('/home');
      } else {
        console.error('Login failed:', res.msg);
        // 设置全局错误信息
        setGlobalError(res.msg || 'Login failed. Please try again.');
      }
    } catch (error) {
      console.error('Login error:', error);
      // 设置全局错误信息
      setGlobalError('Login failed. Please check your network or try again later.');
    } finally {
      setLoading(false);
    }
  };
	return (
		<div className="relative h-screen w-screen overflow-hidden bg-gradient-to-br from-[#0a0a1f] via-[#1f1f3a] to-[#0a0a1f] flex items-center justify-center">
			{/* tsParticles 粒子背景 */}
			<Particles
				id="tsparticles"
				init={particlesInit}
				className="absolute inset-0 z-0"
				options={{
					fullScreen: { enable: false },
					background: { color: 'transparent' },
					particles: {
						number: { value: 100, density: { enable: true, value_area: 1000 } },
						color: { value: ['#8a2be2', '#4b0082', '#7b68ee'] },
						shape: { type: 'circle' },
						opacity: {
							value: 0.6,
							random: true,
							anim: { enable: true, speed: 0.6, opacity_min: 0.3, sync: false },
						},
						size: {
							value: 3.5,
							random: { enable: true, minimumValue: 1 },
							anim: { enable: true, speed: 3, size_min: 0.5, sync: false },
						},
						links: {
							enable: true,
							distance: 140,
							color: '#7b68ee',
							opacity: 0.15,
							width: 0.8,
							blink: false,
							consent: false,
							shadow: { enable: false },
						},
						move: {
							enable: true,
							speed: 0.3,
							direction: 'none',
							random: true,
							straight: false,
							outModes: { default: 'out' },
							attract: { enable: false, rotateX: 600, rotateY: 1200 },
						},
					},
					interactivity: {
						detectsOn: 'canvas',
						events: {
							onHover: { enable: true, mode: 'grab' },
							onClick: { enable: true, mode: 'push' },
							resize: true,
						},
						modes: {
							grab: { distance: 150, links: { opacity: 0.4 } },
							push: { quantity: 4 },
						},
					},
					retina_detect: true,
				}}
			/>

			{/* 登录卡片 */}
			<div className="z-10 backdrop-blur-md bg-white/5 border border-white/10 rounded-2xl p-10 w-[360px] shadow-2xl">
				<div className="text-center mb-8">
				<h1 className="text-2xl font-bold text-white mb-2">AI Matrix</h1>
				<p className="text-gray-300">智能驱动未来</p>
			</div>

      {globalError && (
        <div className="p-3 mb-4 text-sm text-red-400 bg-red-900/20 border border-red-800 rounded-lg">
          {globalError}
        </div>
      )}

			<div className="space-y-4">
				<form 
					onSubmit={onSubmit} 
					className="space-y-4" 
					autoComplete="off"
				>
					<div>
						<div className="relative">
							<div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
								<UserIcon />
							</div>
							<input
								type="text"
								name="username"
								value={formValues.username}
								onChange={handleChange}
								placeholder="Username"
								className="w-full h-12 pl-10 pr-4 py-2 border border-gray-700 rounded-lg bg-white/10 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent transition-all"
								disabled={loading}
							/>
						</div>
						{errors.username && (
							<p className="mt-1 text-sm text-red-400">{errors.username}</p>
						)}
					</div>

					<div>
							<div className="relative">
								<div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
									<LockIcon />
								</div>
								<input
									type={showPassword ? "text" : "password"}
									name="password"
									value={formValues.password}
									onChange={handleChange}
									placeholder="Password"
									className="w-full h-12 pl-10 pr-10 py-2 border border-gray-700 rounded-lg bg-white/10 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent transition-all"
									disabled={loading}
								/>
								<button
									type="button"
									onClick={() => setShowPassword(!showPassword)}
									disabled={loading}
									className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
									aria-label={showPassword ? "Hide password" : "Show password"}
								>
									{showPassword ? <EyeOffIcon /> : <EyeIcon />}
								</button>
							</div>
							{errors.password && (
								<p className="mt-1 text-sm text-red-400">{errors.password}</p>
							)}
						</div>

					<div className="flex items-center justify-between">
						<div className="flex items-center">
							<input
								type="checkbox"
								name="remember"
								checked={formValues.remember}
								onChange={handleChange}
								className="w-4 h-4 text-cyan-500 rounded bg-white/10 border-gray-600 focus:ring-cyan-500 transition-colors"
								disabled={loading}
							/>
							<label htmlFor="remember" className="ml-2 text-sm text-gray-300 cursor-pointer">
								Remember me
							</label>
						</div>
					</div>

					<button
						type="submit"
						disabled={loading}
						className="w-full h-12 bg-gradient-to-r from-cyan-400 to-teal-400 text-white font-medium rounded-lg hover:from-cyan-500 hover:to-teal-500 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:ring-offset-2 transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed disabled:transform-none"
					>
						{loading ? (
							<div className="flex items-center justify-center space-x-2">
								<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
								<span>Logging in...</span>
							</div>
						) : (
							'登录'
						)}
					</button>
				</form>
					{/* <Input
						size="large"
						placeholder="Email"
						prefix={<UserOutlined className="site-form-item-icon" />}
					/>
					<Input.Password
						size="large"
						placeholder="Password"
						prefix={<LockOutlined className="site-form-item-icon" />}
					/>
					<Button
						type="primary"
						size="large"
						block
						className="bg-gradient-to-r from-cyan-400 to-teal-400 border-none"
					>
						登录
					</Button>
					<div className="flex justify-between text-sm text-gray-400">
						<a href="#" className="hover:text-cyan-400 transition">
							忘记密码？
						</a>
						<a href="#" className="hover:text-cyan-400 transition">
							注册账号
						</a>
					</div> */}
				</div>
			</div>
		</div>
	);
}
